import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/device/lock/api.dart";
import "package:ct_pa_majordomo/pages/device/lock/widgets/operation_record/list_item.dart";
import "package:ct_pa_majordomo/pages/device/widgets/device_header.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:ttlock_flutter/ttlock.dart";

class OperationRecord extends StatefulWidget {
  final int lockId;
  final String lockData;
  const OperationRecord({super.key, required this.lockId, required this.lockData});

  @override
  State<StatefulWidget> createState() => _OperationRecordState();

}

class _OperationRecordState extends State<OperationRecord> {
  Map recordType = {
    -5: "人脸开锁",
    -4: "二维码开锁",
     4: "密码开锁",
     7: "IC卡开锁",
     8: "指纹开锁",
    12: "网关开锁",
    55: "遥控开锁",
    92: "管理员密码开锁"
  };

  final ScrollController _scrollController = ScrollController();
  List _list = [];
  int _total = 0;
  bool _isLoading = false;
  Map<String, dynamic> _params = {
    "pageNum": 1,
    "pageSize": 10,
  };

  void _readRecord() {
    EasyLoading.show();
    TTLock.getBluetoothState((state) {
      print("回调：$state");
      if (state == TTBluetoothState.turnOn) {
        TTLock.getLockOperateRecord(TTOperateRecordType.latest, widget.lockData,
          (operateRecord) {
            EasyLoading.showToast("读取成功");
            lockApi.uploadUnlockRecords(widget.lockId, operateRecord);
        }, (errorCode, errorMsg) {
            EasyLoading.showToast(errorMsg);
        });
      }
    });

  }

  void _getRecords() async {
    EasyLoading.show();
    _isLoading = true;
    Map resData = await lockApi.getUnlockRecords(widget.lockId, _params);
    EasyLoading.dismiss();
    _isLoading = false;
    setState(() {
      _list.addAll(resData["rows"] ?? []);
      _total = resData["total"] ?? 0;
    });
  }

  Future<void> _refresh() async {
    _params["pageNum"] = 1;
    _list = [];
    _getRecords();
  }

  void _onScroll() {
    if (_isLoading || _list.length >= _total) return;
    if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
      setState(() {
        _params["pageNum"] += 1;
        _getRecords();
      });
    }
  }

  @override
  void initState() {
    super.initState();
    _getRecords();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  Widget _listItem(Map item) {
    return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {},
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // const Text("2024.09.25", style: TextStyle(color: ThemeVars.colorTextSec),),
            // const SizedBox(height: 6,),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 12),
              decoration: const BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(5)),
                color: Colors.white,
              ),
              child: Row(
                children: [
                  DecoratedBox(
                    decoration: BoxDecoration(
                      color: ThemeVars.colorBackground,
                      borderRadius: BorderRadius.all(Radius.circular(50)),
                    ),
                    child: Icon(Icons.person, size: 50,),
                  ),
                  SizedBox(width: 10,),
                  Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Text(item["username"] ?? "--", style: TextStyle(fontSize: 16,),),
                              // Text("已失效", style: TextStyle(fontSize: 12, color: ThemeVars.colorError),),
                            ],
                          ),
                          SizedBox(height: 4,),
                          Row(
                            children: [
                              Text("${DateTools.formatYMD(item["lockDate"], format: "{y}-{m}-{d} {h}:{i}")}  用${recordType[item["recordType"]]} ${item["success"] == 1 ? "成功" : "失败"}", style: TextStyle(color: ThemeVars.colorTextTer, fontSize: 13),),
                              SizedBox(width: 10,),
                            ],
                          )
                        ],
                      )
                  )
                ],
              ),
            ),
          ],
        )
    );
  }

  @override
  Widget build(BuildContext context) {
    return DeviceHeader(
        title: "操作记录",
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios_new),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        showSearch: false,
        showFloatBtn: false,
        actions: [
          TextButton(
            onPressed: () {
              _readRecord();
            },
            child: const Text("读取记录", style: TextStyle(color: Colors.white),)
          ),
        ],
        children: [
          Positioned(
            width: MediaQuery.of(context).size.width,
            top: 0,
            left: 0,
            child: Container(
              width: MediaQuery.of(context).size.width,
              decoration: const BoxDecoration(
                color: Colors.white,
              ),
              padding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: 6),
              child: const SizedBox(
                height: 40,
                child: TextField(
                  decoration: InputDecoration(
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.all(Radius.circular(5)),
                      borderSide: BorderSide.none
                    ),
                    hintText: "请搜索",
                    isDense: true,
                    filled: true,
                    fillColor: ThemeVars.colorBackground,
                    suffixIcon: SizedBox(
                      child: Icon(Icons.search, size: 20,),
                    ),
                  ),
                  style: TextStyle(fontSize: 14),
                ),
              )
            )
          ),
          Container(
            width: MediaQuery.of(context).size.width,
            margin: const EdgeInsets.only(top: 60, left: ThemeVars.paddingPage, right: ThemeVars.paddingPage),
            child: RefreshIndicator(
              onRefresh: _refresh,
              child: ListView.separated(
                controller: _scrollController,
                itemBuilder: (context, index) {
                  return _listItem(_list[index]);
                },
                separatorBuilder: (context, index) => const SizedBox(height: 12,),
                itemCount: _list.length,
              ),
            ),
          ),
        ]
    );
  }

}